<template>
  <div class="login">
    <!-- 粒子效果 -->
    <Particles id="tsparticles" :particlesInit="particlesInit" :particlesLoaded="particlesLoaded" :options="options" />

    <div class="loginPart">
      <h2>用户登录</h2>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" status-icon label-width="100px" class="demo-ruleForm"
        style="transform:translate(-30px);">
        <el-form-item label="账号：" prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入账号" maxlength="20" clearable />
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="ruleForm.password" type="password" v-on:keyup.enter="handleLogin(ruleFormRef)"
            placeholder="请输入密码" maxlength="20" show-password clearable />
        </el-form-item>
        <div id="btn">
          <el-button type="primary" @click="handleLogin(ruleFormRef)" :loading="btnLoading">登录</el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { loadFull } from 'tsparticles';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus'
import { getEncryptedString } from '@/api/user'
import { encryptCBC } from '@/util/AesUtil'
import { ElNotification } from 'element-plus'
import { timeFix } from '@/util/util'
import { useRouter } from 'vue-router';
const router = useRouter();
//获取userStore
import userStore from '@/store/modules/user';
const user = userStore();

//按钮loading
const btnLoading = ref(false);

//粒子特效参数
const particlesInit = async (engine: any) => {
  await loadFull(engine);
};
const particlesLoaded = async (container: any) => {
  console.log('Particles container loaded', container);
};
const options = reactive({
  background: {
    color: {
      value: '#000', // 粒子颜色
    },
  },
  fpsLimit: 60,
  interactivity: {
    events: {
      onClick: {
        enable: true,
        mode: 'push', // 可用的click模式有: "push", "remove", "repulse", "bubble"。
      },
      onHover: {
        enable: true,
        mode: 'repulse', // 可用的hover模式有: "grab", "repulse", "bubble"。
      },
      resize: true,
    },
    modes: {
      bubble: {
        distance: 400,
        duration: 2,
        opacity: 0.8,
        size: 40,
      },
      push: {
        quantity: 4,
      },
      repulse: {
        distance: 200,
        duration: 0.4,
      },
    },
  },
  particles: {
    color: {
      value: '#ffffff',
    },
    links: {
      color: '#ffffff', // '#dedede'。线条颜色。
      distance: 150, // 线条长度
      enable: true, // 是否有线条
      opacity: 0.5, // 线条透明度。
      width: 1, // 线条宽度。
    },
    collisions: {
      enable: false,
    },
    move: {
      direction: 'none',
      enable: true,
      outMode: 'bounce',
      random: false,
      speed: 2, // 粒子运动速度。
      straight: false,
    },
    number: {
      density: {
        enable: true,
        area: 800,
      },
      value: 80, // 粒子数量。
    },
    opacity: {
      value: 0.5, // 粒子透明度。
    },
    shape: {
      type: 'circle', // 可用的粒子外观类型有："circle","edge","triangle", "polygon","star"
    },
    size: {
      random: true,
      value: 2, // 粒子大小。
    },
  },
  detectRetina: true,
});

//from表单值
const ruleForm = reactive({
  username: '',
  password: '',
});

//form表单校验规则
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  username: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请填写密码', trigger: 'blur' }],
});

/**
 * 登录方法
 */
const handleLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        btnLoading.value = true;
        let encryptMsg = await getEncryptedString();
        if (encryptMsg.code != 200) {
          ElMessage.error(encryptMsg)
          return;
        }
        console.log('获取加密key,', encryptMsg);
        let password = encryptCBC(
          ruleForm.password,
          encryptMsg.data.key,
          encryptMsg.data.iv
        );
        let handleLoginResult = await user.handleLogin({
          username: ruleForm.username,
          password: password,
        });
        if (handleLoginResult == 'ok') {
          console.log('登录成功：', handleLoginResult);
          router.push("/")
          ElNotification({
            title: '欢迎',
            message: `hi，${timeFix()}，欢迎回来`,
            type: 'success',
          })
        } else {
          ElMessage.error("登录报错：" + handleLoginResult)
        }
      } catch (error) {
        ElMessage.error("登录报错::" + error)
      } finally {
        btnLoading.value = false;
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};
/**
 * 重置方法
 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style scoped>
.login {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

.loginPart {
  position: absolute;
  /*定位方式绝对定位absolute*/
  top: 50%;
  left: 50%;
  /*顶和高同时设置50%实现的是同时水平垂直居中效果*/
  transform: translate(-50%, -50%);
  /*实现块元素百分比下居中*/
  width: 450px;
  padding: 50px;
  /*背景颜色为黑色，透明度为0.8*/
  background: rgba(255, 204, 255, 0.3);
  /*box-sizing设置盒子模型的解析模式为怪异盒模型， 将border和padding划归到width范围内*/
  box-sizing: border-box;
  /*边框阴影  水平阴影0 垂直阴影15px 模糊25px 颜色黑色透明度0.5*/
  box-shadow: 0px 15px 25px rgba(0, 0, 0, 0.5);
  /*边框圆角，四个角均为15px*/
  border-radius: 15px;
}

h2 {
  margin: 0 0 30px;
  padding: 0;
  color: #fff;
  text-align: center;
  /*文字居中*/
}

#btn {
  transform: translate(170px);
  width: 80px;
  height: 40px;
  font-size: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>@/api/user/user